package com.example.dw.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.dw.admin.dto.CreateCourseDTO;
import com.example.dw.admin.dto.PageRequestDTO;
import com.example.dw.admin.dto.UpdateCourseDTO;
import com.example.dw.admin.service.AdminCourseService;
import com.example.dw.entity.Course;
import com.example.dw.mapper.CourseMapper;
import com.example.dw.mapper.UserMapper;
import com.example.dw.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理端课程服务实现类
 * @author system
 * @since 2024-01-01
 */
@Slf4j
@Service
public class AdminCourseServiceImpl implements AdminCourseService {

    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<Course> getSomeCourses(Integer count) {
        QueryWrapper<Course> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("createdAt");
        wrapper.last("LIMIT " + count);
        return courseMapper.selectList(wrapper);
    }

    @Override
    public List<Course> getCoursesBySchool(Integer schoolId) {
        QueryWrapper<Course> wrapper = new QueryWrapper<>();
        wrapper.eq("schoolid", schoolId);
        wrapper.orderByDesc("createdAt");
        return courseMapper.selectList(wrapper);
    }

    @Override
    public List<Course> getAllCourses() {
        QueryWrapper<Course> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("createdAt");
        return courseMapper.selectList(wrapper);
    }

    @Override
    public Map<String, Object> getCoursesByPage(PageRequestDTO pageRequest) {
        Page<Course> page = new Page<>(pageRequest.getPage(), pageRequest.getSize());
        QueryWrapper<Course> wrapper = new QueryWrapper<>();
        
        // 添加搜索条件
        if (StringUtils.hasText(pageRequest.getKeyword())) {
            wrapper.like("courseName", pageRequest.getKeyword())
                   .or()
                   .like("difficulty", pageRequest.getKeyword());
        }
        
        // 添加排序
        if (StringUtils.hasText(pageRequest.getSortBy())) {
            if ("desc".equalsIgnoreCase(pageRequest.getSortOrder())) {
                wrapper.orderByDesc(pageRequest.getSortBy());
            } else {
                wrapper.orderByAsc(pageRequest.getSortBy());
            }
        } else {
            wrapper.orderByDesc("createdAt");
        }

        IPage<Course> result = courseMapper.selectPage(page, wrapper);
        
        Map<String, Object> response = new HashMap<>();
        response.put("records", result.getRecords());
        response.put("total", result.getTotal());
        response.put("size", result.getSize());
        response.put("current", result.getCurrent());
        response.put("pages", result.getPages());
        
        return response;
    }

    @Override
    public Course getCourseById(Integer courseid) {
        Course course = courseMapper.selectById(courseid);
        if (course == null) {
            throw new RuntimeException("课程不存在");
        }
        return course;
    }

    @Override
    public void createCourse(CreateCourseDTO createCourseDTO) {
        Course course = new Course();
        BeanUtils.copyProperties(createCourseDTO, course);
        course.setCourseClick(0); // 初始化点击量
        course.setCreatedAt(LocalDateTime.now());
        
        int result = courseMapper.insert(course);
        if (result <= 0) {
            throw new RuntimeException("创建课程失败");
        }
        log.info("成功创建课程: {}", course.getCourseName());
    }

    @Override
    public void updateCourse(UpdateCourseDTO updateCourseDTO) {
        Course existingCourse = courseMapper.selectById(updateCourseDTO.getCourseid());
        if (existingCourse == null) {
            throw new RuntimeException("课程不存在");
        }
        
        Course course = new Course();
        BeanUtils.copyProperties(updateCourseDTO, course);
        
        int result = courseMapper.updateById(course);
        if (result <= 0) {
            throw new RuntimeException("更新课程失败");
        }
        log.info("成功更新课程: {}", course.getCourseid());
    }

    @Override
    public void deleteCourse(Integer courseid) {
        Course course = courseMapper.selectById(courseid);
        if (course == null) {
            throw new RuntimeException("课程不存在");
        }
        
        int result = courseMapper.deleteById(courseid);
        if (result <= 0) {
            throw new RuntimeException("删除课程失败");
        }
        log.info("成功删除课程: {}", courseid);
    }

    @Override
    public List<UserVO> getAllTeachers() {
        // 获取所有角色为教师的用户 (role = 2)
        return userMapper.getUsersByRole(2);
    }
} 